package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //尝试获取一下querystring中的blogid字段
        BlogDao blogDao=new BlogDao();
        String blogId=req.getParameter("blogId");
        if(blogId==null) {
            //如果blogid为空，就是博客列表
            //把数据库中的list集合中的所有信息构造程json格式的字符串发回给浏览器
           // BlogDao blogDao = new BlogDao();
            List<Blog> blogs = blogDao.selectAll();
            //把blogs转换为json格式的字符串
            String respjson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respjson);
        }else{
            //querystring如果存在，就是博客详情页。
            //否则就是博客详情页,指定blogId的博客详情页面
            Blog blog=blogDao.selectById(Integer.parseInt(blogId));
            //如果这个对象是空的就直接抛异常，就是可能出现在url中手动设置querystring访问的情况
            if(blog==null){
                System.out.println("当前的blogId="+blogId+"对应的博客不存在！！");
            }
            String respjson=objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respjson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        HttpSession session=req.getSession(false);
        if(session==null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登陆，无法编写博客");
            return;
        }
        User user= (User) session.getAttribute("user");
        //根据user对象就可以拿到博客作者

        //获取博客标题和正文
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        if(title==null||title.equals("")||content==null||content.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前提交的数据有误！缺少标题或正文");
            return;
        }
        Blog blog=new Blog();
        blog.setContent(content);
        blog.setTitle(title);
        //当前系统的时间
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        blog.setUserId(user.getUserId());
        //将数据插入数据库
        BlogDao blogDao=new BlogDao();
        blogDao.add(blog);
        //跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
